import pymysql
import struct
import datetime 
def dataParse(data):
	analy = []
	analy_1 = []
	datalen = len(data)
	print("数据长度",datalen)
	data = struct.unpack('B'*datalen,data)
	data=list(tuple(data))
	#print(type(data))
	
	if data[0] == 0xAA and data[1] == 0x55 :
		print("数据",data)
		ID = data[3] << 8 | data[2]
		Status = data[4]
		N = data[7]
		if N <=2 :
			print("没有压力值")
		for i in range(14,14+(N-2)*2,2):
			Paska=(data[i]+data[i+1]*256)*(data[8]+data[9]*256)
			analy.append(str(ID))
			analy.append(Status)
			analy.append(str(Paska/1000))
			analy_1.append(analy)
	return analy_1

def wirteDB(data):
	#写入数据库
	# tmp=[]
	# dat = (data[0], data[1],data[2],datetime.datetime.now())
	# tmp.append(dat)
	conn = pymysql.connect("localhost", "root", "    ","gasholder")
	print("连接成功")
	# 使用cursor()方法获取操作游标
	cursor = conn.cursor()
	#2. SQL 插入语句
	sql = """INSERT INTO historydata(tankseg, nbattery,npressurecode, ntime) VALUES ( '%s', '%d', '%s', '%s')"""
	   # 执行sql语句
	cursor.execute(sql %(data[0], data[1],data[2],datetime.datetime.now()))
	#cursor.executemany(sql ,tmp)
	conn.commit()
	print("数据写入数据库成功",datetime.datetime.now())
	# 提交到数据库执行
	# 关闭数据库连接
	conn.close()

if __name__ == '__main__':
	main()